package com.mis.pos.controller;

import com.mis.pos.common.utils.ApiResponse;
import com.mis.pos.common.utils.PageUtil;
import com.mis.pos.dto.ItemNumberDTO;
import com.mis.pos.dto.SaleDTO;
import com.mis.pos.entity.PayEntity;
import com.mis.pos.entity.SaleEntity;
import com.mis.pos.form.PayForm;
import com.mis.pos.service.InventoryService;
import com.mis.pos.service.PayService;
import com.mis.pos.service.SaleItemService;
import com.mis.pos.service.SaleService;
import com.mis.pos.service.impl.SaleServiceImpl;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.web.bind.annotation.*;

import javax.validation.constraints.Max;
import java.util.ArrayList;
import java.util.List;

/**
 * @Description 订单管理控制类
 * @Author yuxiang
 * @CreatedDate 2019/11/14 16:36
 */
@RestController
@RequestMapping("/sale")
public class SaleController {

    /**
     * 日志打印对象
     */
    private Logger logger = LoggerFactory.getLogger(SaleServiceImpl.class);

    @Autowired
    private SaleService saleService;

    @Autowired
    private PayService payService;

    @Autowired
    private SaleItemService saleItemService;

    @Autowired
    private InventoryService inventoryService;

    /**
     * 订单管理处的支付
     * @return
     */
    @PostMapping("/pay")
    public ApiResponse pay(@RequestBody PayForm payForm) {
        ApiResponse<PayEntity> apiResponse = new ApiResponse<>();
        PayEntity payEntity;
        try {

            //1.更改订单状态
            int res1 = saleService.updateSaled(payForm.getSaleId());
            if (res1 == 0){
                //2.生成支付记录,不用更改库存
                payEntity = new PayEntity(payForm.getPayWay(), payForm.getSaleId(), payForm.getAccount());
                int res2 = payService.save(payEntity);
                if (res1==-1 || res2 == -1){
                    return new ApiResponse(-1,"支付失败,数据库操作错误");
                }
            }else {
                return new ApiResponse(-1,"支付失败,数据库操作错误");
            }

        } catch (Exception e) {
            e.printStackTrace();
            return new ApiResponse(-1, "服务器出错！");
        }
        apiResponse.setEvent(0);
        apiResponse.setObj(payEntity);
        apiResponse.setMsg("支付成功");

        return apiResponse;
    }


    /**
     * 订单列表以及查询
     * @param saleId 订单id
     * @param pageNumber 第几页
     * @param pageSize 页中数量
     * @return
     */
    @GetMapping("searchSale")
    public ApiResponse saleList(@RequestParam(value = "saleId",defaultValue = "0")Long saleId,
                                @RequestParam(value = "pageNumber",defaultValue = "1")Integer pageNumber,
                                @RequestParam(value = "pageSize",defaultValue = "10")Integer pageSize){

        ApiResponse apiResponse = new ApiResponse();

        //返回的订单表格中每一条的记录
        List<SaleDTO> saleDTOS = new ArrayList<>();
        //总数
        Integer maxcount = 0;

        try {
            if (saleId==0){
                //如果订单为0，则查询全部
                //1.获取分页订单
                List<SaleEntity> saleEntities = saleService.listSale((pageNumber-1)*pageSize, pageSize);
                //2.查询订单内部的商品列表 todo 优化sql
                for (SaleEntity sale :
                        saleEntities) {
                    List<ItemNumberDTO> itemNumberDTOS = saleItemService.findDTObySaleId(sale.getId());
                    SaleDTO temp = new SaleDTO(sale.getId(),sale.getUpdateTime(),itemNumberDTOS,sale.getCount(),sale.getIsPayed(),sale.getDescription());
                    saleDTOS.add(temp);
                }
                //3.查询总数
                maxcount = saleService.countSales();


            }else {
                //查询订单
                SaleEntity saleEntity = saleService.searchBySaleId(saleId);
                if (saleEntity==null){
                    return new ApiResponse(-1,"订单不存在");
                }else {
                List<ItemNumberDTO> itemNumberDTOS = saleItemService.findDTObySaleId(saleId);
                SaleDTO temp = new SaleDTO(saleEntity.getId(),saleEntity.getUpdateTime(),itemNumberDTOS,saleEntity.getCount(),saleEntity.getIsPayed(),saleEntity.getDescription());
                saleDTOS.add(temp);
                maxcount = 1;
                }

            }
        }catch (Exception e){
            e.printStackTrace();
            return new ApiResponse(-1,"服务器出现错误");
        }
        //向返回对象中添加数据
        apiResponse = PageUtil.pageManual(saleDTOS,pageNumber,pageSize,maxcount);
        return apiResponse;
    }


    /**
     * 退货
     * @param dto 订单dto
     * @return
     */
    @PostMapping("return")
    public ApiResponse returnGoods(@RequestBody SaleDTO dto){
        ApiResponse response = new ApiResponse();
        try {
            //1.删除订单
            int res = saleService.deletSaleById(dto.getId());
            //2.更改库存
            if (res==-1){
                return new ApiResponse(-1,"删除订单失败");
            }
            for (ItemNumberDTO itemNumberDTO :
                    dto.getItemNumberDTOS()) {
                inventoryService.addInventory(itemNumberDTO.getItemId(),itemNumberDTO.getNumber());
            }
            response.setEvent(0);
            response.setMsg("退货成功");
        }catch (Exception e){
            e.printStackTrace();
            return new ApiResponse(-1,"服务器出现错误");
        }
        return response;
    }
}
